/**
 * 个人中心
 * @param  {obj} $scope [description]
 * @param  {obj} Page   factory
 * @param  {obj} Token  factory
 * @return {obj}        [description]
 */
function ctrl_person($scope, Page, Token) {
    Page.setTitle('个人中心');
    //头像
    $scope.headImg = headImg = sessionStorage.getItem("headImg");
    Token.get(function() {
        $scope.headImg = headImg = sessionStorage.getItem("headImg");
    })
}

/**
 * 个人中心-查看农场
 * @return {} [description]
 */
function ctrl_person_farmer($scope, $http, Page, Token, $state) {
    Page.setTitle('我的农场');
    var xhr = new Jsonp($http);
    var hint = new Popup($scope, 'hintdate');

    var indent_url = _SERVER_ + "/myFarmGet?access_token=" + _ACCESSTOKEN_ + "&callback=JSON_CALLBACK";
    xhr.get(indent_url, function(data) {
        if (data.result == 1) {
            log(data)
            $scope.farms = data.farms;
            if (arr_empty($scope.farms)) {
                $scope.isFarmer = false;
            }
        } else alert("系统繁忙，稍后尝试。")
    });

    $scope.pay_manage = function(id) {
        $scope.paydata.show = true;
        $scope.paydata.myFarmId = id;
    }

    /**
     * hint init
     * @type {Object}
     */
    $scope.hintdate = {
        content: '',
        show: false
    };

    function hint_delay(content) {
        $scope.hintdate = {
            content: content,
            show: false
        };
        hint.delay(4000);
    }

    $scope.paydata = {
        myFarmId: '',
        months: '',
        title: "艺术菜园",
        show: false,
        cost: 0,
        items: [{
            name: "1",
            id: "1"
        }, {
            name: "3",
            id: "3"
        }, {
            name: "5",
            id: "5"
        }, {
            name: "一次付完",
            id: "0"
        }],
        item_select: function(mth) {
            log(mth)
            var myFarmId = $scope.paydata.myFarmId;
            var months = mth.id;
            $scope.paydata.months = mth.id;
            manager_cost(myFarmId, months, function(data) {
                log(data)
                $scope.paydata.cost = data.price;
            });
        },
        close: function() {
            log('close')
            $scope.paydata.cost = 0;
            $scope.paydata.show = false;
        },
        pay: function() {
            if ($scope.paydata.months) {
                sessionStorage.setItem("manege_myFarmId", $scope.paydata.myFarmId);
                sessionStorage.setItem("manege_months", $scope.paydata.months);
                location.href = "http://wx.imlenong.com/pay/pay_manage.html";
            } else hint_delay("请选择续费月份数");
        }
    }

    $scope.date_transfer = function(date) {
        // log(date)
        return date.split(" ")[0];
    }

    function manager_cost(myFarmId, months, callback) {
        var indent_url = _SERVER_ + "/cropManageOrderAddPrice?access_token=" + _ACCESSTOKEN_ + "&myFarmId=" + myFarmId + "&months=" + months + "&callback=JSON_CALLBACK";
        xhr.get(indent_url, function(data) {
            callback(data)
        });
    }

    // var farms_data_t = {
    //     "farms": [{
    //         "addTime": "2016-10-11 18:42:24",
    //         "buyCrop": 0,
    //         "expireDate": "2017-10-11 00:00:00",
    //         "farmId": 1,
    //         "id": 4,
    //         "myCropModel": [{
    //             "addTime": "2016-10-10 00:00:00",
    //             "cropId": 1,
    //             "cropName": "油菜心",
    //             "cropStatus": 0,
    //             "grownDay": 50,
    //             "grownUpDay": 20,
    //             "id": 7,
    //             "manage": 1,
    //             "myFarmId": 4,
    //             "orderId": 161,
    //             "sow": 0,
    //             "sowDate": "2016-10-10 00:00:00",
    //             "status": 1,
    //             "userId": 10000000,
    //             "image": "http://wx.imlenong.com/weChat/images/bbq.jpg"
    //         }, {
    //             "addTime": "2016-10-10 00:00:00",
    //             "cropId": 2,
    //             "cropName": "小白菜",
    //             "cropStatus": 0,
    //             "grownDay": 50,
    //             "grownUpDay": 20,
    //             "id": 8,
    //             "manage": 1,
    //             "myFarmId": 4,
    //             "orderId": 161,
    //             "sow": 0,
    //             "sowDate": "2016-10-10 00:00:00",
    //             "status": 1,
    //             "userId": 10000000,
    //             "image": "http://wx.imlenong.com/weChat/images/bbq2.jpg"
    //         }],
    //         "orderId": 161,
    //         "status": 1,
    //         "updateTime": "2016-10-11 18:42:24",
    //         "userId": 10000000
    //     }],
    //     "msg": "获取成功",
    //     "result": 1
    // };

    // $scope.farms = farms_data_t.farms;

    // log($scope.farms)

    $scope.isFarmer = true;

    $scope.add_seed = function(farm) {
        log(farm)
        if (farm.buyCrop) {
            $state.go('activity.seed', {
                farmId: farm.id,
                buyCrop: farm.buyCrop
            });
        } else log("greens limited");
    }
    $scope.buy_crop = function(buyCrop) {
        log(buyCrop)
        if (buyCrop) return true;
        else return false;
    }
    $scope.crop_status = function(status) {
        // log(status,'status')
        switch (status) {
            case 0:
                return "未播种";
                break;
            case 1:
                return "成长中";
                break;
            case 2:
                return "已成熟";
                break;
            case 3:
                return "已采摘";
                break;
            case -1:
                return "已枯萎";
                break;
        }
    }

    function arr_empty(arr) {
        if (arr.length == 0)
            return true;
        else return false;
    }
}
/**
 * 个人中心-查看代养
 * @return {} [description]
 */
function ctrl_person_animal($scope, $http, Page, Token, $state) {
    Page.setTitle('查看代养');
    var xhr = new Jsonp($http);
    // var dialog = new Popup($scope, 'toastdata');
    var hint = new Popup($scope, 'hintdate');

    $scope.isCultivation = true;
    get_animal_msg();
    Token.get(function(data) {
        get_animal_msg();
    });
    $scope.date_transfer = function(date) {
        // log(date)
        return date.split(" ")[0];
    }
    $scope.name_transfer = function(type) {
        // log(type)
        switch (type) {
            case 1:
                return "生态鸡";
            case 2:
                return "小鸭";
            case 3:
                return "小鹅";
        }
    };
    $scope.pay_manage = function(obj) {
        $scope.paydata.show = true;
        $scope.paydata.myFowlId = obj.id;
        $scope.paydata.title = $scope.name_transfer(obj.fowlModel.fowlType);
        log($scope.paydata.myFowlId, "ID")
    }

    /**
     * hint init
     * @type {Object}
     */
    $scope.hintdate = {
        content: '',
        show: false
    };

    function hint_delay(content) {
        $scope.hintdate = {
            content: content,
            show: false
        };
        hint.delay(4000);
    }

    $scope.paydata = {
        myFowlId: '',
        months: '',
        title: "",
        show: false,
        cost: 0,
        items: [{
            name: "1",
            id: "1"
        }, {
            name: "2",
            id: "2"
        }, {
            name: "3",
            id: "3"
        }, {
            name: "5",
            id: "5"
        }],
        item_select: function(mth) {
            log(mth)
            var months = mth.id;
            var myFowlId = $scope.paydata.myFowlId;
            $scope.paydata.months = mth.id; //更新月份
            manager_cost(myFowlId, months, function(data) {
                log(data)
                $scope.paydata.cost = data.price;
            });
        },
        close: function() {
            log('close')
            $scope.paydata.cost = 0;
            $scope.paydata.show = false;
        },
        pay: function() {
            if ($scope.paydata.months) {
                sessionStorage.setItem("manege_myFowlId", $scope.paydata.myFowlId);
                sessionStorage.setItem("manege_animal_months", $scope.paydata.months);
                location.href = "http://wx.imlenong.com/pay/pay_manage_animal.html";
            } else hint_delay("请选择续费月份数");
        }
    }

    function manager_cost(myFowlId, months, callback) {
        var indent_url = _SERVER_ + "/myFowlManageOrderAddPrice?access_token=" + _ACCESSTOKEN_ + "&myFowlId=" + myFowlId + "&months=" + months + "&callback=JSON_CALLBACK";
        xhr.get(indent_url, function(data) {
            callback(data)
        });
    }
    /**
     * 获取订单数据
     * @return {} [description]
     */
    function get_animal_msg() {
        var url = _SERVER_ + "/myFowlGet?access_token=" + _ACCESSTOKEN_ + "&callback=JSON_CALLBACK";
        xhr.get(url, function(data) {
            log(data)
            $scope.animals = data.fowls;
            if (data.fowls.length == 0) {
                $scope.isCultivation = false;
            }
        })
    }
}
/**
 * 个人中心-订单
 * @param  {obj} $scope [description]
 * @param  {obj} $http  [description]
 * @param  {obj} Token  factory
 * @param  {obj} Page   factory
 * @return {obj}        [description]
 */
function ctrl_person_indent_fin($scope, $http, Token, Page) {
    Page.setTitle('我的订单');
    var xhr = new Jsonp($http);
    var dialog = new Popup($scope, 'toastdata');
    get_indent_msg();
    Token.get(function(data) {
        get_indent_msg();
    });
    /**
     * 获取订单数据
     * @return {} [description]
     */
    function get_indent_msg() {
        var indent_url = _SERVER_ + "/myOrderGet?access_token=" + _ACCESSTOKEN_ + "&callback=JSON_CALLBACK";
        xhr.get(indent_url, function(data) {
            log(data)
            $scope.my_goods = data.orders[0].myGoods;
            $scope.my_indent = data.orders;
        })
    }

    /**
     * list数据加载（repeat）完成（dom）时，渲染二维码
     * @return {} [description]
     */
    $scope.renderFinish = function() {
        console.log('render end')

        for (var i = $scope.my_indent.length - 1; i >= 0; i--) {
            log($scope.my_indent[i].id)
            var id = $scope.my_indent[i].id;
            id = id.toString(); //需要转为字符串
            var selector = "#qrcode" + id;
            var str = toUtf8(id);
            $(selector).qrcode(id);
            // $(selector).qrcode({
            //     render: "table",
            //     width: 200,
            //     height: 200,
            //     text: id.toString()
            // });
        }
    };
    /**
     * 订单状态切换
     * @param  {string} status [description]
     * @return {}        [description]
     */
    $scope.indent_status = function(status) {
        status = status.toString();
        switch (status) {
            case '1':
                return '';
            case '2':
                return 'indent-cancel-ing';
            case '3':
                return 'indent-cancel-fin';
            default:
                log(status)
        }
    };
    /**
     * 取消订单
     * @param  {id} id [description]
     * @return {}    [description]
     */
    $scope.cancel_indent = function(id) {
        $scope.toastdata = {
            title: '确认',
            content: '取消订单后请耐心等待工作人员为您办理退款。',
            hint: '',
            show: false,
            btn_ok_show: true,
            close: function() {
                dialog.close();
            },
            ok: function() {
                dialog.close();
                var cancel_indent_url = _SERVER_ + "/myOrderCancel?access_token=" + _ACCESSTOKEN_ + "&orderId=" + id + "&callback=JSON_CALLBACK";
                xhr.get(cancel_indent_url, function(data) {
                    log(data);
                    if (data.result == '1') {
                        //重新获取订单信息
                        get_indent_msg();
                    } else {
                        alert(data.msg);
                    }
                });

            }
        };
        dialog.open();
    }

    // $scope.goods_type = function(type) {
    //     switch (type) {
    //         case 1:
    //             return '普通商品'
    //             break;
    //         case 2:
    //             return '优惠套餐'
    //             break;
    //         case 3:
    //             return '土地商品'
    //             break;
    //         default:
    //             return '其他'
    //             break;
    //     }
    // }
    /**
     * 编码转换算法
     * @param  {string} str [description]
     * @return {}     [description]
     */
    function toUtf8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }

}

function ctrl_person_indent_unfin($scope, $http, Token, Page) {
    var xhr = new Jsonp($http);
    var dialog = new Popup($scope, 'toastdata');
    get_indent_msg();
    Token.get(function(data) {
        get_indent_msg();
    });
    /**
     * 获取订单数据
     * @return {} [description]
     */
    function get_indent_msg() {
        var indent_url = _SERVER_ + "/myOrderGet?access_token=" + _ACCESSTOKEN_ + "&callback=JSON_CALLBACK";
        xhr.get(indent_url, function(data) {
            log(data)
            $scope.my_goods = data.orders[0].myGoods;
            $scope.my_indent = data.orders;
        })
    }
    /**
     * 订单状态切换
     * @param  {string} status [description]
     * @return {}        [description]
     */
    $scope.indent_status = function(status) {
        status = status.toString();
        switch (status) {
            case '1':
                return '';
            case '2':
                return 'indent-cancel-ing';
            case '3':
                return 'indent-cancel-fin';
            default:
                log(status)
        }
    };
    $scope.content_toggle = false;
    $scope.bool_toggle = function(bool, name) {
        if (bool) {
            $scope[name] = false;
        } else $scope[name] = true;
        log($scope.content_toggle)
    }
}
